import sensor
import image
import lcd
import time

# 初始化屏幕和字库
lcd.init(freq=15000000)
image.font_load(image.UTF8, 16, 16, 0xA00000)  # 必须确保字库烧录到此地址

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)
clock = time.clock()

qr_text = ""
last_qr = ""

# 字体尺寸
CHAR_W = 16
CHAR_H = 16

# 屏幕区域限制
MAX_WIDTH = 300
MAX_HEIGHT = 240
MAX_COLS = MAX_WIDTH // CHAR_W   # 每行最多字符数
MAX_ROWS = MAX_HEIGHT // CHAR_H  # 最多行数

def draw_utf8_text(img, text, x=0, y=0):
    row = 0
    col = 0
    for char in text:
        if row >= MAX_ROWS:
            break
        img.draw_string(x + col * CHAR_W, y + row * CHAR_H, char, color=(0, 255, 0), scale=1)
        col += 1
        if col >= MAX_COLS:
            col = 0
            row += 1

while True:
    clock.tick()
    img = sensor.snapshot()
    codes = img.find_qrcodes()

    if codes:
        qr_text = codes[0].payload()
        img.draw_rectangle(codes[0].rect(), color=(255, 0, 0))

        if qr_text != last_qr:
            print("识别到二维码内容：", qr_text)
            last_qr = qr_text

    # 显示二维码文本内容（逐字绘制，防止重叠）
    draw_utf8_text(img, qr_text, 0, 0)

    lcd.display(img)
